import java.io.IOException;
import java.util.Arrays;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


public class Receiver {

	public static void main(String[] args) throws IOException, InterruptedException {
		
		//final String hostC = "192.168.1.100";
		//final String hostR = "192.168.1.106";
		final String hostR ="127.0.0.1";
		final String hostC = "127.0.0.1";
		final InetAddress IPChannel = InetAddress.getByName(hostC);
		final int portChannel = 65432;
		final int portReceiver = 65433;
		final int portACK = 65434;
		final InetAddress IPReceiver = InetAddress.getByName(hostR);
		final int H = 16;
		
		
		DatagramSocket receiverSocket = new DatagramSocket(portReceiver);
		DatagramSocket ACKsocket = new DatagramSocket(portACK);
		double y = ping(hostC)/2;
		long tempo = System.currentTimeMillis();
		HandshakerR HS = new HandshakerR(IPChannel, portChannel, IPReceiver, portReceiver, portACK,  y, H, receiverSocket, ACKsocket);
		HS.start();
		
		double x = HS.getx();
		int Lr = HS.getLr();
		int N = HS.getN();
		
		InetAddress IPDestination = HS.getIPDestinatio();
		int portDestination = HS.getPortDestination();
		
		Packet firstMessage = HS.getFirstMessage();
		
		System.out.println("Ping x: "+2*x+" N: "+N+" Lr: "+Lr);
		
		Packet[] tabella = new Packet[N];
		Controller daemon = new Controller(receiverSocket, tabella, firstMessage, N, Lr, ACKsocket, IPChannel);
		daemon.runCR();
		long tempo1 = System.currentTimeMillis();
		double tot = (tempo1-tempo)/1000;
		System.out.println("File ricevuto. Tempo totale: "+tot + "s. Numero pacchetti:" +N + "Lunghezza Lr: " +Lr);
		
	}
	
	public static double ping (String hostC) throws IOException {
		
		PingArguments arguments = new PingArguments.Builder().url(hostC)
				.timeout(5000).count(5).bytes(32).build();
		
		PingResult results = Ping.ping(arguments, Ping.Backend.UNIX);
		return results.rtt_avg();
	
	}

}
